<template>
  <!-- 左边菜单 -->
  <div id="layout">
    <RouterView v-if="validateSpecialPage(`${$route.fullPath}`)" :key="$route.fullPath" />
    <el-container :class="layoutSkin" v-else>
      <el-aside class="common-box">
        <div class="action-box">
          <div class="flex justify-center logobox">
            <div @click="backhome" class="logo flex justify-center solid-bottom padding-tb-xs cursor">
              <img v-if="layoutSkin === 'skin-gray'" src="../assets/logo.png" alt />
              <img v-else src="../assets/images/Logo.png" alt />
            </div>
          </div>
          <div class="btns-box">
            <div class="flex justify-center btn-item center cursor margin-bottom-sm leftBox" v-for="(item, index) in menuToolList" :key="index" :class="{ leftBoxActive: store.leftActiveIndex == index }" @click="goto(item.url, index, item.id, item)">
              <div class="menusBox">
                <div class="text-center">
                  <el-icon size="19" class="icon">
                    <component :is="item.icon" v-if="item.icon"></component>
                  </el-icon>
                </div>
                <el-tooltip class="box-item" effect="dark" :content="item.title" placement="top-start" v-if="item.title.length > 8">
                  <div class="menuName">{{ item.title }}</div>
                </el-tooltip>
                <div class="menuName" v-else>{{ item.title }}</div>
              </div>
            </div>
          </div>
        </div>
        <div class="menuBoxLeft cursor">
          <el-icon size="21" color=" #fff" @click="gotoPage('/home')" class="backHomeIcon">
            <Menu />
          </el-icon>
        </div>
      </el-aside>
      <el-main>
        <RouterView :key="$route.fullPath" />
        <!-- <vxe-modal v-model="showDrawerBulk" title="最大化显示" width="600" height="400" show-zoom resize fullscreen>
          <template #default> -->
        <el-drawer ref="drawerBulkRef" v-model="showDrawerBulk" :withHeader="false" :modal="false" modal-class="drawerBulkModal" :show-close="false" :size="'calc(100vw - ' + 70 + 'px)'" style="height: 100%" close-on-click-modal direction="rtl" class="drawerBulk">
          <!-- <template #default> -->
          <div class="bulkMain">
            <!-- 批次审核 抽屉页面 -->
            <LabOperationReviewed v-if="pathTitle === '批次审核'" ref="LabOperationReviewedRef" @closeDrawer="closeDrawer"></LabOperationReviewed>

            <!-- 批次打印 抽屉界面 -->
            <LabBatchPrinted v-if="pathTitle === '批次打印'" ref="LabBatchPrintedRef" @closeDrawer="closeDrawer"></LabBatchPrinted>

            <!-- 批次输入 抽屉页面 -->
            <LabOperationInput v-if="pathTitle === '批次输入'" ref="LabOperationInputRef" @closeDrawer="closeDrawer"></LabOperationInput>

            <!-- 批次调整 抽屉页面 -->
            <LabOperationAdjust v-if="pathTitle === '批次调整'" ref="LabOperationAdjustRef" @closeDrawer="closeDrawer"></LabOperationAdjust>

            <!-- 报告查询 抽屉页面 -->
            <ReportSearch v-if="pathTitle === '报告查询'" ref="ReportSearchRef" @closeDrawer="closeDrawer"></ReportSearch>

            <!-- 报告项目 抽屉页面 -->
            <LabItemDict v-if="pathTitle === '项目维护'" ref="LabItemDictRef" @closeDrawer="closeDrawer"></LabItemDict>

            <!-- 不合格标本 抽屉页面  -->
            <UnqualifiedSpecimens v-if="pathTitle === '不合格标本'" ref="UnqualifiedSpecimensRef" @closeDrawer="closeDrawer"></UnqualifiedSpecimens>
          </div>
          <!-- </template> -->
        </el-drawer>
        <!-- </template>
        </vxe-modal> -->
      </el-main>

      <!-- 检验者弹框页面 -->
      <!-- <LabReviewer ref="LabReviewerRef" @closeSHowApproveConfirm="ApproveConfirmOk" /> -->
      <!-- 原始弹框 -->
      <ChkAuthComp ref="ChkAuthCompRef" @closeSHowApproveConfirm="ApproveConfirmOk" />
      <!-- 标本合并 -->
      <TestListMerge ref="TestListMergeRef" />
      <!-- 切换仓库 -->
      <InvStoreChange ref="InvStoreChangeRef" />
    </el-container>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted, getCurrentInstance, watch } from 'vue';
import { AppStore } from '../stores/store';
import { IsEmpty } from '../utils/common';
//import { fa } from 'element-plus/es/locale';
import { GetGolbalOptions } from '@/utils/SysOptionsHelper';
import ChkAuthComp from '@/components/ChkAuthComp.vue'; //审核者弹框新页面
import TestListMerge from '@/views/lab_sys/lab_bus/components/TestListMerge.vue'; //标本合并
import LabOperationReviewed from '@/views/lab_sys/lab_set/LabOperationReviewed.vue'; //批次审核
import LabBatchPrinted from '@/views/lab_sys/lab_bus/LabBatchPrinted.vue'; //批次打印
import LabOperationInput from '@/views/lab_sys/lab_set/LabOperationInput.vue'; //批次输入
import LabOperationAdjust from '@/views/lab_sys/lab_set/LabOperationAdjust.vue'; //批次调整
import ReportSearch from '@/views/lab_sys/lab_set/Reportsearch.vue'; //报告查询
import LabItemDict from '@/views/lab_sys/lab_set/LabItemDict.vue'; //报告项目(项目维护)
import UnqualifiedSpecimens from '@/views/lab_sys/lab_set/UnqualifiedSpecimens.vue'; //不合格标本
import { LocGet, LocPost } from '@/utils/LocRequestHelper';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
import InvStoreChange from '@/views/inv_sys/inv_bus/InvStoreChange.vue';

let ChkAuthCompRef: any = ref(null); //绑定的审核者页面的标记ref
let LabOperationReviewedRef: any = ref(null); //绑定的批次审核界面的标记ref
let LabBatchPrintedRef: any = ref(null); //绑定的批次打印界面的标记ref
let LabOperationInputRef: any = ref(null); //绑定的批次输入界面的标记ref
let LabOperationAdjustRef: any = ref(null); ////绑定的批次调整界面的标记ref
let ReportSearchRef: any = ref(null); //绑定的报告查询界面的标记ref
let LabItemDictRef: any = ref(null); //绑定的报告项目(项目维护)界面的标记ref
let UnqualifiedSpecimensRef: any = ref(null); //绑定的不合格标本界面的标记ref

let TestListMergeRef: any = ref(null); //标本合并
let currentBulkValue: any = reactive({ code: null, name: '' }); //当前的批量操作

let store = AppStore();
let menuList: any = reactive([]);
let menuToolList: any = reactive([]);
let { proxy }: any = getCurrentInstance();
// 默认获取vuex中的类名
let layoutSkin = ref(store.layoutSkin);
let _beforeUnload_time = '';
let _gap_time = '';

/**切换仓库弹窗组件对象 */
const InvStoreChangeRef = ref(null);

watch(
  () => store.layoutSkin,
  (n, o) => {
    // 将获取的新值动态赋给layoutcolor
    layoutSkin.value = n;
  },
  { deep: true, immediate: true }
);

/**监听是否关闭全局抽屉变量变化 */
watch(
  () => store.isCloseDrawer,
  (n, o) => {
    closeDrawer();
  },
  { deep: true, immediate: false }
);

watch(() => store.isReloadLeftTools, (n, o) => {
  getMenuList();
}, { deep: true, immediate: false });
// let contWidth = ref(0);
// let contHeight = ref(0);
// let isCollapse = ref(true); //当前菜单是否折叠

// 获取模块id
// watch(()=>moduleId,(newval,oldval)=>{
//   console.log('6666666',newval,oldval);
//   getMenuList();
// },{deep: true,immediate:true})

// 高亮项
let leftindexactive = ref('');

getMenuList();

// 获取菜单树型数据
function getMenuList() {
  // 通过权限信息获取菜单1
  menuToolList.length = 0;
  menuList.length = 0;
  const moduleId = localStorage.getItem('moduleId');
  let moduleMenuMap = store.userInfo.moduleMenuMap;
  if (moduleMenuMap && typeof moduleMenuMap === 'object' && Object.keys(moduleMenuMap).length > 0) {
    if (Object.keys(moduleMenuMap).includes(moduleId)) {
      //menuList.push(...moduleMenuMap[moduleId]);
      const arr = moduleMenuMap[moduleId].filter((p) => p.isAssembly === '0' || p.isAssembly === null);
      const toolsArr = moduleMenuMap[moduleId];
      Object.assign(menuList, arr);
      toolsArr.forEach((item) => {
        // 遍历原始数据
        if (item.isTool === '1') {
          // 判断isTool是否为1
          menuToolList.push(item); // 将满足条件的项添加到新数组中
        }
        if (item.children && item.children.length > 0) {
          // 如果有子项，则继续遍历子项
          const fliterMenus = item.children; //.filter(p => p.isAssembly === '0');
          fliterMenus.forEach((childItem) => {
            if (childItem.isTool === '1') {
              // 判断子项的isTool是否为0
              menuToolList.push(childItem); // 将满足条件的子项添加到新数组中
            }
          });
        }
      });
    }
  }
}

let pathUrl = ref(''); //记录当前点击的路由
let prevRoute = ref(''); //记录当前点击的前一个路由

let pathTitle = ref('');

// 点击菜单 跳转页面/打开抽屉/展开弹框
function goto(path: any, index, menuId = null, item: any) {
  if (item && !IsEmpty(item.title) && item.title === '重启接口') {
    const reboot = LocPost((window as any).apiUrl.VUE_APP_LOCAL_PRINT_URL + '/api/InstrumentInterfaceApp/re-boot', { a: '' }); /**重启仪器接口 */
    reboot.then((b) => {
      console.log('重启接口已调用', b);
    });
    return;
  }
  // leftindexactive.value = index;
  const moduleId = localStorage.setItem('curMenuId', IsEmpty(menuId) ? null : menuId);
  store.setLeftActiveIndex(index, path);
  leftindexactive.value = store.leftActiveIndex;
  localStorage.setItem('indexActive', '88');
  localStorage.setItem('activeIndex', '0-0');

  // 记录当前路由地址
  pathUrl.value = path;
  // 记录前一个路由地址
  prevRoute.value = proxy.$router.currentRoute.value.path;
  // 记录当前点击的菜单名字
  pathTitle.value = item.title;
  if (item.isTool === '1' && item.openWith === 'drawer') {
    //item.isAssembly === '1' &&
    // openDrawer(); //打开批次审核抽屉页面
    handleBulkOperation({ code: item.code, title: item.title });
  } else if (item.isTool === '1' && item.openWith === 'modal') {
    //item.isAssembly === '1' &&
    openApproveConfirm(item); //打开检验者弹框页面
  } else {
    closeDrawer(); //点击其他菜单时 也同样关闭抽屉
    proxy.$router.push({ path: path });
  }
}

// -------------------------------------------------------------------------
let showDrawerBulk = ref(false); //批量操作抽屉  是否打开
let isSHowApproveConfirm = ref(false); //是否打开检验者弹框 而不跳转路由

// 批量操作抽屉
function handleBulkOperation(val: any) {
  currentBulkValue = val;
  showDrawerBulk.value = true;
  proxy.$nextTick(() => {
    if (val.title === '批次审核') {
      LabOperationReviewedRef.value?.init(prevRoute.value, showDrawerBulk.value); //传过去前一个路由地址 +抽屉打开状态
    } else if (val.title === '批次打印') {
      LabBatchPrintedRef.value?.init(prevRoute.value, showDrawerBulk.value);
    } else if (val.title === '批次输入') {
      LabOperationInputRef.value?.init(prevRoute.value, showDrawerBulk.value);
    } else if (val.title === '批次调整') {
      LabOperationAdjustRef.value?.init(prevRoute.value, showDrawerBulk.value);
    } else if (val.title === '报告查询') {
      ReportSearchRef.value?.init(prevRoute.value, showDrawerBulk.value);
    } else if (val.title === '项目维护') {
      LabItemDictRef.value?.init(prevRoute.value, showDrawerBulk.value);
    } else if (val.title === '不合格标本') {
      UnqualifiedSpecimensRef.value?.init(prevRoute.value, showDrawerBulk.value);
    }
  });
}

// 关闭抽屉drawer
function closeDrawer() {
  currentBulkValue = { code: null, name: '' };
  showDrawerBulk.value = false;
}

// ---------------------------------------------------------------------
//检验者页面,弹窗
function openApproveConfirm(item) {
  if (item && !IsEmpty(item.id)) {
    if (item.url === 'ChkAuthComp') {
      isSHowApproveConfirm.value = true;
      ChkAuthCompRef.value?.initPage(isSHowApproveConfirm.value, '审核者', null);
    }
    if (item.url === 'TestListMerge') {
      TestListMergeRef.value?.initPage(localStorage.getItem('sampleDateNow'));
    }
    if (item.url === 'invstorechange') {
      InvStoreChangeRef.value?.initPage();
    }
  }
}

// 取消关闭弹框组件_检验者
function ApproveConfirmOk() {
  isSHowApproveConfirm.value = false;
}

// -------------------------------------------------------------------------

// 批次审核界面(上方注释了此方法)
function openDrawer() {
  // showDrawerBulk.value = true;
  // const outerDiv: any = (document.querySelector('.el-drawer').parentNode.style.inset =
  //   '50px 0 0 70px');
  showDrawerBulk.value = !showDrawerBulk.value;
  proxy.$nextTick(() => {
    LabOperationReviewedRef.value?.init(prevRoute.value, showDrawerBulk.value); //传过去前一个路由地址 +抽屉打开状态
  });
}

// -------------------------------------------------------------------------
//#region  Watch监听路由变化
watch(
  () => proxy.$router.currentRoute.value.path,
  (newValue, oldValue) => {
    if (store.leftRouterUrl == newValue) {
      // console.log('不清空');
    } else {
      leftindexactive.value = '99';
    }
    getMenuList();
  },
  { deep: true }
);

onMounted(() => {
  try {
    const a = LocPost((window as any).apiUrl.VUE_APP_LOCAL_PRINT_URL + '/api/Home/get-is-start', { a: '' }); /**验证本地打印服务是否开启 */
    if (a) {
      a.then((b) => {
        if (b) {
          sessionStorage.setItem('locserstart', true);
        } else {
          sessionStorage.setItem('locserstart', false);
        }
      });
    }
    GetGolbalOptions();
  } catch (error) {
    //todo
  }
  window.addEventListener('beforeunload', (e) => beforeunloadHandler(e));
  window.addEventListener('unload', (e) => unloadHandler(e));
});

let beforeunloadHandler = (e) => {
  _beforeUnload_time = new Date().getTime();
  //e.returnValue = '关闭提示'; 弹窗
};
let unloadHandler = (e) => {
  _gap_time = new Date().getTime() - _beforeUnload_time;
  //判断是窗口关闭还是刷新
  if (_gap_time <= 20) {
    localStorage.removeItem('token');
    localStorage.removeItem('userInfo');
    localStorage.removeItem('layoutSkin');
    // localStorage.removeItem('remUser');
    // 如果没有记住密码(若是记住密码就不用在本地清空)
    if (store.remUser.remPwd !== true) {
      localStorage.removeItem('remUser');
      store.remUser = '';
    }
  }
};

onUnmounted(() => {
  window.removeEventListener('beforeunload', (e) => beforeunloadHandler(e));
  window.removeEventListener('unload', (e) => unloadHandler(e));
});

function gotoPage(path: string) {
  localStorage.removeItem('indexActive');
  localStorage.removeItem('activeIndex');
  proxy.$routerObj.push({ path: path });
  closeDrawer();
}
function backhome() {
  proxy.$router.push('/home');
  localStorage.setItem('indexActive', '88');
  localStorage.setItem('activeIndex', '0-0');
  closeDrawer();
}
/**验证是否是病区查看报告界面 */
function validateSpecialPage(path: String) {
  if (!IsEmpty(path) && path.toLowerCase().lastIndexOf('wkltbyhis') >= 0) {
    return true;
  }
  if (!IsEmpty(path) && path.toLowerCase().lastIndexOf('crireportchk') >= 0) {
    return true;
  }
  if (!IsEmpty(path) && path.toLowerCase().lastIndexOf('criReportReceive') >= 0) {
    return true;
  }
  if (!IsEmpty(path) && path.toLowerCase().lastIndexOf('criReportHandle') >= 0) {
    return true;
  }
  return false;
}
</script>
<style lang="scss" scoped>
#layout {
  width: calc(100vw);
  height: calc(100vh);
  background-color: $bg-white;

  .el-container {
    width: 100%;
    height: 100%;
    overflow-y: auto;
    overflow-x: hidden;
  }

  .el-main {
    padding: 0 !important;

    /* 设置滚动条的宽度、高度、背景色和边框样式 */
  }

  .common-box {
    width: 70px;
    display: flex;
    flex-direction: column;
    //justify-content: space-between;
    height: 100vh;
    background-color: $left-menu-bg1;
    flex-wrap: wrap;
    border-right: solid 1px $left-menu-bg1;
    overflow: hidden;
    border: none;

    .action-box {
      position: relative;
      width: 70px;
      height: calc(100vh - 50px);
      overflow-y: hidden;
      background-color: $left-menu-bg2;

      .logo {
        height: 46px;
        width: 70px;

        img {
          width: 50px;
          height: 50px;
        }
      }

      .btns-box {
        height: calc(100vh - 50px - 56px);
        flex-wrap: nowrap;
        width: 100%;
        overflow-y: auto;
        // padding-left: 3px;

        .leftBox {
          // justify-items: center;
          background: linear-gradient(to bottom, $left-menu-item-bg1, $left-menu-item-bg2);
          box-shadow: 0px 1px 0px $left-menu-active-color, 0px 0px 0px $left-menu-boxshadow;
          border-top: 1px solid $left-menu-top-border;
          border-radius: 10px;
          width: 60px !important;
          color: $base-white;
          margin: 5px 0 5px 4px;
          font-size: 12px;
          text-align: center;
        }

        .leftBoxActive {
          background: $base-white;
          color: $left-menu-active-color;
          border-top: 1px solid $left-menu-top-border;
          box-shadow: 0px 1px 0px $left-menu-active-color, 0px 0px 0px $left-menu-boxshadow;
          border-radius: 10px;
          width: 60px !important;
          margin-top: 5px;
          margin-bottom: 5px;
        }

        .btn-item {
          font-weight: 400;
          width: 65px;
          height: 62px;
          cursor: pointer;
          box-sizing: border-box;
        }
      }

      /* 设置滚动条的宽度、高度、背景色和边框样式 */
      ::-webkit-scrollbar {
        width: 0px;
        height: 10px;
        background-color: rgba(0, 0, 0, 0);
        border-radius: 0px;
      }

      /* 设置滚动条滑块的背景色和圆角 */
      ::-webkit-scrollbar-thumb {
        background-color: $border-color-1;
        border-radius: 0px;
      }

      /* 设置滚动条滑块在悬停状态下的背景色和圆角 */
      ::-webkit-scrollbar-thumb:hover {
        background-color: $font-color-3;
        border-radius: 0px;
      }

      /* 设置滚动条轨道的背景色和圆角 */
      ::-webkit-scrollbar-track {
        background-color: $blue-light;
        border-radius: 0px;
      }

      /* 设置滚动条轨道在悬停状态下的背景色和圆角 */
      ::-webkit-scrollbar-track:hover {
        background-color: $border-color-1;
        border-radius: 0px;
      }
    }

    // /* 设置滚动条的宽度、高度、背景色和边框样式 */
  }

  .el-main {
    overflow-x: hidden;
  }

  .logoBox {
    background-color: $top-menu-bg1;
  }

  .red {
    background-color: red !important;
  }

  .yellow {
    background-color: yellow !important;
  }

  .blue {
    background-color: blue !important;
  }
}

.bulkMain {
  height: 100%;
}

.menusBox {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;

  .menuName {
    padding: 0 2px;
    display: inline-block;
    display: -webkit-box;
    /* 使用Webkit的弹性盒模型显示 */
    -webkit-line-clamp: 2;
    /* 显示的行数，例如2行 */
    -webkit-box-orient: vertical;
    /* 设置或检索伸缩盒对象的子元素的排列方式 */
    overflow: hidden;
    /* 隐藏超出容器的内容 */
    text-overflow: ellipsis;
    /* 超出部分显示省略号 */
  }
}

.menuBoxLeft {
  background-color: $left-menu-bg2;
  width: 100%;
  height: 50px;
  line-height: 50px;
  text-align: center;

  .backHomeIcon {
    &:hover {
      // width: 100%;
      // height:50px;
      // line-height: 50px;
      // background-color: #48729e;
    }
  }
}
</style>

<style lang="scss">
.el-drawer__body {
  padding: 0;
}

.drawerBulkModal {
  z-index: 1000;
  inset: 50px 0 0 70px !important;
}
</style>
